package zmee.pur.src.common;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.common.constant.BillAssistConstant;
import kd.scm.common.util.DynamicObjectUtil;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.constant.SrcCommonConstant;
import kd.scm.pds.common.constant.SrcMetadataConstant;
import kd.scm.pds.common.util.PdsCommonUtils;
import kd.scm.src.common.score.SrcScoreContext;
import kd.scm.src.common.score.SrcScoreHelper;
import kd.scm.src.common.score.result.SrcScoreHandleAptitude;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2023/02/27/16:45
 * @Description: 评分--结果处理--合格最低分、是否合格、资审结果
 */
public class SrcScoreHandleAptitudeExt extends SrcScoreHandleAptitude {
    @Override
    public void process(SrcScoreContext context) {
        // 非资质预审、资质后审的评分不需要处理
        if (!SrcScoreHelper.isAptitudeScore1(context) && !SrcScoreHelper.isAptitudeScore2(context)) {
            return;
        }
        // 门槛未达标的资审任务单
        Set<Long> underThresholdSet = getUnderThresholdSet(context);
        // 获取 资审任务
        DynamicObject[] scoreTaskObjs = getScoreTaskObjs(context);
        // 获取 资审结果
        DynamicObject[] resultObjs = getAptitudeResultObjs(context);

        for (DynamicObject scoreTaskObj : scoreTaskObjs) {
            // 更新 合格最低分、是否合格、资审结果
            updateAptitudeResult(scoreTaskObj, underThresholdSet, resultObjs);
        }
        // 批量保存
        PdsCommonUtils.saveDynamicObjects(scoreTaskObjs);
        PdsCommonUtils.saveDynamicObjects(resultObjs);
    }

    /**
     * 更新 合格最低分、是否合格、资审结果
     *
     * @param scoreTaskObj
     */
    @Override
    protected void updateAptitudeResult(DynamicObject scoreTaskObj, Set<Long> underThresholdSet, DynamicObject[] resultObjs) {
        // 方案最低分: 为0才需要获取
        BigDecimal minScore = scoreTaskObj.getBigDecimal(SrcCommonConstant.MINVALUE);
        if (minScore.compareTo(BigDecimal.ZERO) <= 0) {
            DynamicObject schemeObj = scoreTaskObj.getDynamicObject(BillAssistConstant.SCHEME);
            minScore = schemeObj.getBigDecimal(SrcCommonConstant.SUMSCORE);
            scoreTaskObj.set(SrcCommonConstant.MINVALUE, minScore);
        }
        boolean isValid = false;
        if (!underThresholdSet.contains(scoreTaskObj.getPkValue())) {
            // 指标占比(%)
            BigDecimal indexScore = scoreTaskObj.getBigDecimal(SrcCommonConstant.BILLINDEXSCORE);
            BigDecimal sumScore = scoreTaskObj.getBigDecimal(SrcCommonConstant.SUMSCORE);
            // 当前得分×100 >= 最低得分×指标占比(%)
            if (sumScore.multiply(new BigDecimal(100)).compareTo(minScore.multiply(indexScore)) >= 0) {
                // 合格
                scoreTaskObj.set(SrcCommonConstant.ISVALID, "1");
                isValid = true;
            }
        }

        // 更新 资审结果
        updateAptidudeResult(resultObjs, SrmCommonUtil.getPkValue(scoreTaskObj), isValid);
    }

    /**
     * 更新资审结果
     *
     * @param resultObjs
     * @param billId
     * @param isValid
     */
    private void updateAptidudeResult(DynamicObject[] resultObjs, long billId, boolean isValid) {
        List<DynamicObject> rows =
                Arrays.stream(resultObjs).filter(e -> e.getLong(SrcCommonConstant.SCORETASK + '.' + SrcCommonConstant.ID) == billId).collect(Collectors.toList());
        for (DynamicObject row : rows) {
            if (isValid) {
                // 通过
                row.set(SrcCommonConstant.ISAPTITUDE, "1");
            } else {
                // 不通过
                row.set(SrcCommonConstant.ISAPTITUDE, "2");
            }
        }
    }

    /**
     * 获取 未满足门槛值的任务单Set
     *
     * @param context
     * @return
     */
    private Set<Long> getUnderThresholdSet(SrcScoreContext context) {
        // 当前资审单号
        QFilter qFilter = new QFilter(SrcCommonConstant.BILLID, QCP.in, context.getScoreTaskSet());
        // 门槛值未达标
        qFilter.and(SrcCommonConstant.ISOVERTHRESHOLD, QCP.equals, Boolean.TRUE);
        // 基本类型过滤
        qFilter.and(SrcScoreHelper.getBaseTypeFilter(context,
                SrcCommonConstant.BILLID + '.' + SrcCommonConstant.INDEXTYPE + '.' + SrcCommonConstant.BASETYPE));
        // 未满足门槛值的任务单Set
        DynamicObjectCollection rows = QueryServiceHelper.query(SrcMetadataConstant.SRC_SCOREANALYSE,
                SrcCommonConstant.BILLID + '.' + SrcCommonConstant.ID, qFilter.toArray());
        return rows.stream().map(e -> e.getLong(SrcCommonConstant.BILLID + '.' + SrcCommonConstant.ID)).collect(Collectors.toSet());
    }

    // 获取 资审任务单
    private DynamicObject[] getScoreTaskObjs(SrcScoreContext context) {
        String selectFields = DynamicObjectUtil.getSelectfields(SrcMetadataConstant.SRC_SCORETASK, false);
        QFilter qfilter = new QFilter(SrcCommonConstant.ID, QCP.in, context.getScoreTaskSet());
        return BusinessDataServiceHelper.load(SrcMetadataConstant.SRC_SCORETASK, selectFields, qfilter.toArray());
    }

    /**
     * 获取 资质结果记录
     *
     * @param context
     * @return
     */
    @SuppressWarnings("rawtypes")
    private DynamicObject[] getAptitudeResultObjs(SrcScoreContext context) {
        String entityName = SrcMetadataConstant.SRC_APTITUDERESULTF7;
        //基本类型
        Object baseType = context.getParamMap().get(SrcCommonConstant.BASETYPE);
        if (baseType instanceof List && ((List) baseType).contains(SrcCommonConstant.BASETYPE_APTITUDE2)) {
            entityName = SrcMetadataConstant.SRC_APTITUDERESULT2F7;
        } else if (baseType instanceof Set && ((Set) baseType).contains(SrcCommonConstant.BASETYPE_APTITUDE2)) {
            entityName = SrcMetadataConstant.SRC_APTITUDERESULT2F7;
        } else if (baseType.equals(SrcCommonConstant.BASETYPE_APTITUDE2)) {
            entityName = SrcMetadataConstant.SRC_APTITUDERESULT2F7;
        }
        String selectFields = DynamicObjectUtil.getSelectfields(entityName, false);
        QFilter qfilter = new QFilter(SrcCommonConstant.SCORETASK, QCP.in, context.getScoreTaskSet());
        return BusinessDataServiceHelper.load(entityName, selectFields, qfilter.toArray());
    }
}
